import { computed, ref } from 'vue'

export default function useCodeCount(numDefault = 60, btnShowDefault = '获取短信验证码') {
  const num = ref<number>(numDefault)
  const timer = ref<any>(null)
  const isCounting = ref<boolean>(false)

  const codeBtnShow = computed(() => {
    return num.value === 60 ? btnShowDefault : `${num.value}秒后重试`
  })

  function startCounting() {
    if (timer.value || num.value !== numDefault) {
      return
    }

    isCounting.value = true

    timer.value = setInterval(() => {
      num.value -= 1

      if (num.value <= 0) {
        isCounting.value = false
        num.value = numDefault
        clearInterval(timer.value)
        timer.value = null
      }
    }, 1000)
  }

  return { codeBtnShow, startCounting, isCounting }
}
